package com.ziq.zcamp.community

import android.annotation.SuppressLint
import android.graphics.Color
import android.graphics.Rect
import android.os.Bundle
import android.view.View
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.blankj.utilcode.util.ScreenUtils
import com.facebook.drawee.backends.pipeline.Fresco
import com.ziq.base.base.BaseFragment
import com.ziq.base.extension.binding
import com.ziq.base.extension.click
import com.ziq.base.extension.dp
import com.ziq.zcamp.R
import com.ziq.zcamp.bean.post.PostingDetail
import com.ziq.zcamp.bean.user.UserRelationListItem
import com.ziq.zcamp.constant.FollowRelation
import com.ziq.zcamp.databinding.FragmentCommunityFollowBinding
import com.ziq.zcamp.login.ActionAfterLogin
import com.ziq.zcamp.login.LoginActivity
import com.ziq.zcamp.manager.*
import com.ziq.zcamp.mine.PersonalHomePageActivity
import com.ziq.zcamp.post.PostingAdapter
import com.ziq.zcamp.view.StatusView
import com.ziq.zcamp.view.layoutmanager.CustomStaggeredGridLayoutManager
import dagger.hilt.android.AndroidEntryPoint
import kotlin.math.abs

@AndroidEntryPoint
class CommunityFollowFragment : BaseFragment(R.layout.fragment_community_follow){

    val mViewModel: CommunityFollowViewModel by viewModels()
    private val binding : FragmentCommunityFollowBinding? by binding()

    var postingAdapter: CommunityPostingAdapter? = null
    var itemWidth:Int = 0
    var communityFollowAdapter : CommunityFollowAdapter? = null
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding?.root
        itemWidth = (ScreenUtils.getScreenWidth() - GlobalContextManager.getResources().getDimensionPixelSize(R.dimen.dimens_dip_24)) / 2

        DataManager.postingVersion.observe(viewLifecycleOwner, Observer<Int> {
            if(isResume){
                refreshList = true
                updateStatus()
            }
        })

        DataManager.followStatusVersion.observe(viewLifecycleOwner, Observer<Int> {
            if(isResume && binding?.flFollow?.visibility == View.GONE){
                refreshList = true
                updateStatus()
            }
        })
    }

    var isResume = false
    var refreshPostingVersion :Int? = null
    var followStatusVersion :Int? = null
    override fun onResume() {
        super.onResume()
        isResume = true
        if(refreshPostingVersion == null && DataManager.postingVersion.value != null){
            refreshList = true
        } else if(refreshPostingVersion != null && (DataManager.postingVersion.value ?: 0) > refreshPostingVersion!!){
            refreshList = true
        }
        refreshPostingVersion = DataManager.postingVersion.value

        if(followStatusVersion == null && DataManager.followStatusVersion.value != null){
            refreshList = true
        } else if(followStatusVersion != null && (DataManager.followStatusVersion.value ?: 0) > followStatusVersion!!){
            refreshList = true
        }
        followStatusVersion = DataManager.followStatusVersion.value

        updateStatus()
    }

    override fun onPause() {
        super.onPause()
        isResume = false
    }

    fun updateStatus(){
        if(UserManager.instance.isLogin.value == true){
            mViewModel.requestUserNumRelation(onSuccess = {
                if(it.data?.isNotEmpty() == true){
                    var following = it.data!![0].num_followings
                    var postCount = it.data!![0].num_post
                    if(following > 0 || postCount > 0){
                        updateListStatus()
                    } else {
                        updateFollowStatus()
                    }
                }
            }, onFail = {
            })
        } else {
            updateLogoutStatus()
        }
    }

    //未登陆样式
    fun updateLogoutStatus(){
        refreshList = true
        if(postingAdapter != null){
            postingAdapter?.setData(mutableListOf())
            binding?.recycleView?.adapter = postingAdapter
        }
        binding?.flLogout?.visibility = View.VISIBLE
        binding?.flFollow?.visibility = View.GONE
        binding?.flList?.visibility = View.GONE
        binding?.logoutStatusView?.setStatus(StatusView.NO_DATA,
            isCenter = false,
            marginTop = 60.dp,
            imgSrc = R.drawable.pic_no_content_camp,
            imgWidth = 235.dp,
            imgHeight = 151.dp,
            msg = "登录查看我的关注～",
            updateActionBtn = { btn ->
                btn.setText("立即登录")
                btn.setTextColor(Color.parseColor("#FFFFFF"))
                btn.setBackgroundResource(R.drawable.selector_book_btn)
                btn.click {
                    LoginActivity.open(GlobalContextManager.appContext!!)
                }
            }
        )
        DataManager.changeCommunityPostingBtnShow(false)
    }

    //未关注样式
    fun updateFollowStatus(){
        refreshList = true
        //避免显示上次内容
        if(postingAdapter != null){
            postingAdapter?.setData(mutableListOf())
            binding?.recycleView?.adapter = postingAdapter
        }
        binding?.flLogout?.visibility = View.GONE
        binding?.flFollow?.visibility = View.VISIBLE
        binding?.flList?.visibility = View.GONE
        if(communityFollowAdapter == null){
            communityFollowAdapter = CommunityFollowAdapter("fotab_rec")
            binding?.rvFollowRecommend?.layoutManager = LinearLayoutManager(context)
            binding?.rvFollowRecommend?.adapter = communityFollowAdapter

            mViewModel.followStatusShow.observe(viewLifecycleOwner, Observer<Int> {
                when(it){
                    StatusView.IDLE -> {
                        binding?.followStatusView?.setStatus(StatusView.IDLE)
                    }
                    StatusView.LOADING -> {
                        binding?.followStatusView?.setStatus(StatusView.LOADING)
                    }
                    StatusView.NO_DATA -> {
                        binding?.followStatusView?.setStatus(StatusView.NO_DATA, backgroundColor = Color.parseColor("#ffffff"))
                    }
                    StatusView.NET_ERROR -> {
                        binding?.followStatusView?.setStatus(StatusView.NET_ERROR, backgroundColor = Color.parseColor("#ffffff"))
                    }
                }
            })

            mViewModel.followList.observe(viewLifecycleOwner, Observer<MutableList<UserRelationListItem>> {
                communityFollowAdapter?.setData(it)
                updateFollowRefreshBtn()
            })
            communityFollowAdapter?.onRelationUpdateClick =  {
                updateFollowRefreshBtn()
            }

            binding?.followRefresh?.click {
                updateStatus()
            }

        }
        mViewModel.requestFollowList()
        DataManager.changeCommunityPostingBtnShow(false)

    }

    fun updateFollowRefreshBtn(){
        var show = false
        val list = communityFollowAdapter?.getData()
        if(list?.isNotEmpty() == true){
            for (item in list){
                if(item.relation == FollowRelation.mutual.value || item.relation == FollowRelation.following.value){
                    show = true
                    break
                }
            }
        }
        if(show){
            binding?.followRefresh?.visibility = View.VISIBLE
        } else {
            binding?.followRefresh?.visibility = View.GONE
        }
    }


    //列表样式
    var refreshList = true
    fun updateListStatus(){
        binding?.flLogout?.visibility = View.GONE
        binding?.flFollow?.visibility = View.GONE
        binding?.flList?.visibility = View.VISIBLE
        if(postingAdapter == null && isAdded){
            postingAdapter = CommunityPostingAdapter(requireContext(), lifecycle, itemWidth)

            binding?.recycleView?.layoutManager = CustomStaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
            binding?.recycleView?.addItemDecoration(object : RecyclerView.ItemDecoration() {
                override fun getItemOffsets(
                    outRect: Rect,
                    view: View,
                    parent: RecyclerView,
                    state: RecyclerView.State
                ) {
                    super.getItemOffsets(outRect, view, parent, state)
                    val pos = parent.getChildAdapterPosition(view)
                    if (pos in 0..1 ){
                        outRect.top = 8.dp
                    }else{
                        outRect.top = 0
                    }
                }
            })
            binding?.recycleView?.adapter = postingAdapter
            binding?.recycleView?.addOnScrollListener(object : RecyclerView.OnScrollListener() {
                override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                    super.onScrollStateChanged(recyclerView, newState)
                    if (Fresco.hasBeenInitialized() && newState == RecyclerView.SCROLL_STATE_IDLE) {
                        Fresco.getImagePipeline().resume()//恢复加载图片
                    }
                }

                override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                    super.onScrolled(recyclerView, dx, dy)
                    if(abs(dy) > 25){
                        if(Fresco.hasBeenInitialized() && !Fresco.getImagePipeline().isPaused){
                            Fresco.getImagePipeline().pause()// 暂停图片请求
                        }
                    } else if(abs(dy) < 5){
                        if(Fresco.hasBeenInitialized() && Fresco.getImagePipeline().isPaused){
                            Fresco.getImagePipeline().resume()//恢复加载图片
                        }
                    }
                }
            })

            postingAdapter?.setAction(object : PostingAdapter.PostingAdapterAction {
                override fun itemClick(item: PostingDetail) {
                    PostManager.navigateToDetailActivity(
                        this@CommunityFollowFragment.requireActivity(),
                        item
                    )
                }

                override fun userInfoClick(item: PostingDetail) {
                    PersonalHomePageActivity.open(this@CommunityFollowFragment.requireContext(), item.user?.uid?:0)
                }
            })

            mViewModel.listStatusShow.observe(viewLifecycleOwner, Observer<Int> {
                when(it){
                    StatusView.IDLE -> {
                        binding?.statusView?.setStatus(StatusView.IDLE)
                    }
                    StatusView.LOADING -> {
                        binding?.statusView?.setStatus(StatusView.LOADING)
                    }
                    StatusView.NO_DATA -> {
                        binding?.statusView?.setStatus(StatusView.NO_DATA,
                            isCenter = false,
                            marginTop = 60.dp,
                            imgSrc = R.drawable.pic_no_content_camp,
                            imgWidth = 235.dp,
                            imgHeight = 151.dp,
                            msg = "暂无内容～",
                            updateActionBtn = { btn ->
                                btn.setText("抢首发")
                                btn.setTextColor(Color.parseColor("#FFFFFF"))
                                btn.setBackgroundResource(R.drawable.selector_book_btn)
                                btn.click {
                                    LoginActivity.checkLogin(object : ActionAfterLogin {
                                        @SuppressLint("CheckResult")
                                        override fun action() {
                                            GlobalContextManager.mainHandler.postDelayed({
                                                if(activity != null){
                                                    PostManager.showPostTypeSelector(requireActivity())
                                                }
                                            }, 500)
                                        }
                                    })
                                }
                            }
                        )
                    }
                    StatusView.NET_ERROR -> {
                        binding?.statusView?.setStatus(StatusView.NET_ERROR, isCenter = false, marginTop = 130.dp, updateActionBtn = { btn ->
                            btn.click {
                                mViewModel.onRefresh(true)
                            }
                        })
                    }
                }
            })

            mViewModel.listRequestFinished.observe(viewLifecycleOwner, Observer<Boolean> {
                if(it == true){
                    binding?.refreshLayout?.finishRefresh()
                    binding?.refreshLayout?.finishLoadMore()
                }
            })
            mViewModel.listHasMore.observe(viewLifecycleOwner, Observer<Boolean> {
                if(it == true){
                    binding?.refreshLayout?.resetNoMoreData()
                } else {
                    binding?.refreshLayout?.setNoMoreData(true)
                }
            })

            mViewModel.list.observe(viewLifecycleOwner) {
                postingAdapter?.setData(it)
                DataManager.changeCommunityPostingBtnShow(it.isNotEmpty())
            }

            binding?.refreshLayout?.setOnRefreshListener {
                mViewModel.onRefresh(false)
                PostManager.requestSubject()
                CampLifeManager.requestMyCampData()
            }
            binding?.refreshLayout?.setOnLoadMoreListener {
                mViewModel.onLoadMore()
            }

            UserManager.instance.postingLike.observe(viewLifecycleOwner, Observer {
                postingAdapter?.notifyDataSetChanged()
            })

            mViewModel.onRefresh(true)

        } else if(refreshList){
            refreshList = false
            binding?.recycleView?.scrollToPosition(0)
            mViewModel.onRefresh()
        } else {
            DataManager.changeCommunityPostingBtnShow(mViewModel.list.value?.isNotEmpty() == true)
        }
    }

}